# coding: utf-8
class CodeparterController < ApplicationController

	def index

		return unless checkAdmin

		# 获取已创建的代码块
		@codelist = Codeparter.where(:isdeleted => 0).order('updated_at DESC')

		# 获取单条代码块详情
		if(params["id"] != nil)
			@codeinfo = Codeparter.find(params["id"])
		else
			@codeinfo = Codeparter.new if(@codeinfo == nil)
		end

		# 设置模板路径
		render :template => 'admin/codeparter.html.erb'
	end

	# POST: 保存代码块
	def save
		return unless checkAdmin
		_success = false
		if(params[:name] != nil and params[:title] != nil)
			if(params[:id] == nil || params[:id] == '')
				cp = Codeparter.new
			else
				cp = Codeparter.find(params[:id])
			end
			if(cp != nil)
				cp.name = params[:name]
				cp.title = params[:title]
				cp.content = params[:content]
				cp.isdeleted = 0 # 默认未删除状态
				_success = cp.save
			end
		end
		render :text => if(_success) then 1 else 0 end
	end

	# POST: 删除代码块
	def delete
		return unless checkAdmin
		_success = false
		if(params[:id] != nil && params[:id] != '')
			cp = Codeparter.find(params[:id])
			if(cp != nil)
				cp.isdeleted = 1 # 设置为删除状态
				_success = cp.save
			end
		end
		render :text => if(_success) then 1 else 0 end
	end

	# 静态方法：获取指定代码块
	def CodeparterController.getByName(name)
		cp = Codeparter.where(:isdeleted => 0, :name => name)
		if(cp != nil && cp.size > 0)
			cp[0].content
		end
	end

end
